﻿using System;
using System.Collections.Generic;

namespace Microsoft.Popfly.GameCreator.GameEngine.Events
{
    public class Filter
    {
        internal Dictionary<String, bool> Scenes;

        private List<PropertyCondition> m_propertyConditions = new List<PropertyCondition> ();

        private Dictionary<String, bool> m_states;

        private Game m_game;
        private PropertyHolder m_owner;

        public bool CheckFilter()
        {
            foreach (PropertyCondition condition in m_propertyConditions)
            {
                if (!condition.CheckCondition())
                    return false;
            }

            // Behavior won't be added if the behavior owner's scene doesn't match
            //if (Scenes != null && Scenes.ContainsKey(m_game.CurrentScene.Name) && !Scenes[m_game.CurrentScene.Name])
            //{
            //    return false;
            //}
			// Apparently we can also have an empty states filter that means all states are valid (even though if there is even one key, states not in the collection are invalid)
            if (m_states != null && m_states.Count != 0 && (!m_states.ContainsKey(((Actor) m_owner).CurrentState.Name) || !m_states[((Actor)m_owner).CurrentState.Name]))
            {
                return false;
            }

            return true;
        }

        public Filter(Game game, PropertyHolder owner, Data.FilterInfo filterInfo)
        {
            m_game = game;
            m_owner = owner; 
            Scenes = null;
            m_states = null;

            if (filterInfo.PropertyConditions != null)
            {
                foreach (Data.PropertyConditionInfo propInfo in filterInfo.PropertyConditions)
                {
                    m_propertyConditions.Add(new PropertyCondition(owner, game, propInfo));
                }
            }

            if (filterInfo.SceneReferences != null)
            {
                Scenes = new Dictionary<String, bool>();
                foreach (KeyValuePair<String, Data.SceneReferenceInfo> kvp in filterInfo.SceneReferences)
                {
                    Scenes[kvp.Key] = true;
                }
            }

            if (filterInfo.StateReferences != null)
            {
                m_states = new Dictionary<String, bool>();
                foreach (KeyValuePair<String, Data.StateReferenceInfo> kvp in filterInfo.StateReferences)
                {
                    m_states[kvp.Key] = true;
                }
            }
        }
    }
}